<!-- src/views/admin/Orders.vue -->
<template>
  <AdminPage
    title="订单管理"
    :filters="filters"
    :pagination-enabled="true"
    v-model:page="page"
    :total="total"
    :page-size="pageSize"
  >
    <!-- 筛选栏 -->
    <template #filters>
      <el-form-item label="订单号" class="filter-item">
        <el-input v-model="filters.orderNo" placeholder="请输入" clearable size="small" />
      </el-form-item>
      <el-form-item label="用户名称" class="filter-item">
        <el-input v-model="filters.username" placeholder="请输入" clearable size="small" />
      </el-form-item>
      <el-form-item label="订单状态" class="filter-item">
          <el-select v-model="filters.status" placeholder="请选择" clearable size="small" @change="handleStatusChange">
            <!-- <el-option label="待支付" :value="0" /> -->
            <el-option label="已支付" :value="1" />
            <el-option label="已退款" :value="2" />
          
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" class="filter-item">
        <div class="date-picker-container">
          <el-date-picker
            v-model="filters.time"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            size="small"
          />
        </div>
      </el-form-item>
      <el-form-item class="filter-item">
        <el-button type="primary" :icon="Search" @click="handleSearch" size="small">搜索</el-button>
        <el-button @click="handleReset" size="small">重置</el-button>
      </el-form-item>
    </template>

    <!-- 表格 -->
    <template #table>
      <el-table :data="pageData" border stripe header-cell-class-name="table-header" class="order-table" v-loading="loading">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="orderNo" label="订单号" min-width="140" />
        <el-table-column prop="username" label="用户名称" min-width="120" />
        <el-table-column prop="requestAmount" label="支付金额" min-width="100" />
        <el-table-column prop="createdTime" label="创建时间" min-width="180" />
        <el-table-column prop="completedTime" label="完成时间" min-width="180" />
        <el-table-column prop="status" label="订单状态" min-width="100">
          <template #default="{ row }">
            <el-tag v-if="row.status===1" type="success">已支付</el-tag>
            <el-tag v-else-if="row.status===2" type="warning">已退款</el-tag>
            <el-tag v-else type="info">待支付</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" v-if="filters.status==1">
          <template #default="{ row }">
            <el-button 
              v-if="Number(row.status)===1" 
              type="danger" 
              size="small"
              @click="handleRefund(row.orderNo)"
            >
              退款
            </el-button>
          </template>
        </el-table-column>
        
      </el-table>
    </template>

    <template #pagination></template>
  </AdminPage>
</template>

<script setup lang="ts">
import { computed, reactive, ref, onMounted, watch } from 'vue'
import { Search } from '@element-plus/icons-vue'
import AdminPage from '../../components/admin/AdminPage.vue'
import { ElMessage } from 'element-plus'
import {getBalanceOrder,OrderRefund} from '../../api/admin'

type Order = {
  orderNo: string
  username: string
  requestAmount: number
  createdTime: string
  completedTime: string
  status: number
}

const filters = reactive({
  orderNo: '',
  username: '',
  time: [] as string[] | [],
  status: 1
})
const allData = ref<Order[]>([])
const page = ref(1)
const pageSize = ref(8)
const total = ref(0)
const loading = ref(false)

//根据用户名和订单号分页查询用户余额支付订单
const getBalanceOrderBykeyword=async()=>{
  loading.value = true
  try{
    // 处理空值情况
    const username = filters.username || ''
    const orderNo = filters.orderNo || ''
    
    const res=await getBalanceOrder(page.value, pageSize.value, username, orderNo, filters.status || 1)
    console.log('搜索结果:', res.data);
    
    if (res && res.data) {
      allData.value = res.data.items || []
      total.value = res.data.total || 0
    }else{
      ElMessage.error('获取订单数据失败')
    }
  }catch(error){
    console.error('获取订单数据异常:', error)
    ElMessage.error('获取订单数据异常')
  }finally{
    loading.value = false
  }
}
// 处理退款
const handleRefund=async(orderNo:string)=>{
  try{
     const res= await OrderRefund(orderNo)
     console.log('退款结果:', res);
     if(res.data.code===0){
      ElMessage.success('退款成功')
      getBalanceOrderBykeyword()
     }else{
      ElMessage.error('退款失败')
     }
  }catch(error){
    console.error('退款异常:', error)
    ElMessage.error('退款异常')
  }
}

// 初始化加载数据
onMounted(() => {
  getBalanceOrderBykeyword()
})

// 时间筛选
const filteredData = computed(() => {
  return allData.value.filter(row => {
    const matchNo = !filters.orderNo || row.orderNo.includes(filters.orderNo)
    const matchUser = !filters.username || row.username.includes(filters.username)
    const matchStatus = !filters.status || row.status=== filters.status
    
    // 时间范围筛选
    let matchTime = true
    if (filters.time && filters.time.length === 2) {
      const createdTime = new Date(row.createdTime).getTime()
      const startTime = new Date(filters.time[0]).getTime()
      const endTime = new Date(filters.time[1]).getTime()
      matchTime = createdTime >= startTime && createdTime <= endTime
    }
    
    return matchNo && matchUser && matchStatus && matchTime
  })
})

const pageData = computed(() => {
  // 由服务端分页，表格直接展示当前页数据
  return filteredData.value
})

// 搜索按钮点击事件
const handleSearch = () => {
  page.value = 1
  getBalanceOrderBykeyword()
}

// 订单状态变化时立即重新加载数据
const handleStatusChange = () => {
  page.value = 1
  getBalanceOrderBykeyword()
}
const handleReset = () => {
  filters.orderNo = ''
  filters.username = ''
  filters.time = []
  filters.status = 1
  page.value = 1
  getBalanceOrderBykeyword()
}
// 分页事件由 AdminPage 统一触发（v-model:page）

// 监听分页参数变化，重新请求数据
watch([page, pageSize], () => {
    getBalanceOrderBykeyword()
})
</script>
